package com.qyhl.webtv.commonlib.utils.service;


import android.app.Notification;
import android.app.NotificationManager;
import android.app.Service;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.IBinder;
import androidx.annotation.Nullable;
import androidx.core.content.FileProvider;
import android.widget.RemoteViews;
import android.widget.Toast;

import com.orhanobut.hawk.Hawk;
import com.qyhl.webtv.basiclib.utils.DateUtils;
import com.qyhl.webtv.basiclib.utils.StringUtils;
import com.qyhl.webtv.basiclib.utils.network.EasyHttp;
import com.qyhl.webtv.basiclib.utils.network.callback.DownloadProgressCallBack;
import com.qyhl.webtv.basiclib.utils.network.exception.ApiException;
import com.qyhl.webtv.commonlib.R;
import com.qyhl.webtv.commonlib.common.CommonUtils;
import com.qyhl.webtv.commonlib.constant.PathConfigConstant;

import java.io.File;

import es.dmoral.toasty.Toasty;

/**
 * Created by qyhl on 2017/12/6.
 * 版本更新服务
 */

public class VersionService extends Service {
    private String apkUrl;
    private String versionName;

    private NotificationManager manager;
    private RemoteViews remoteViews;
    private Notification notification;
    private int pro;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onStart(Intent intent, int startId) {
        super.onStart(intent, startId);
        if (intent == null) {
            stopSelf();
            PathConfigConstant.isLoading = false;
            Hawk.put("isLoading", PathConfigConstant.isLoading);
            return;
        }
        apkUrl = intent.getStringExtra("loadUrl");
        versionName = intent.getStringExtra("versionName");

        if (StringUtils.isEmpty(apkUrl)) {
            stopSelf();
            PathConfigConstant.isLoading = false;
            Hawk.put("isLoading", PathConfigConstant.isLoading);
            return;
        } else {
            startDownLoad(apkUrl);
        }

    }


    /**
     * 开始下载
     *
     * @param url
     */
    private void startDownLoad(String url) {
        //设置apk名称
        StringBuffer sb = new StringBuffer(PathConfigConstant.APK_NAME);
        sb.insert(sb.indexOf("."), "_V" + versionName + DateUtils.getDate());
        final String path = Environment.getExternalStorageDirectory().getPath() + PathConfigConstant.Apk;
        pro = -1;

        EasyHttp.downLoad(url)
                .savePath(path)
                .saveName(sb.toString())//不设置默认名字是时间戳生成的
                .execute(new DownloadProgressCallBack<String>() {
                    @Override
                    public void update(long bytesRead, long contentLength, boolean done) {
                        int progress = (int) (bytesRead * 100 / contentLength);

                        int i = (int) (progress * 100);
                        if (i > pro) {
                            pro = i;
//                            setNotification((int) (progress * 100));
                            setNotification(progress);
                        }

                        if (done) {//下载完成
                        }
                    }

                    @Override
                    public void onStart() {
                        //开始下载
                    }

                    @Override
                    public void onComplete(String path) {
                        //下载完成，path：下载文件保存的完整路径
                        PathConfigConstant.isLoading = false;
                        Hawk.put("isLoading", PathConfigConstant.isLoading);
                        if (manager != null) {
                            manager.cancel(PathConfigConstant.NOTIFICATION_ID);
                        }
                        installApk(new File(path));
                    }

                    @Override
                    public void onError(ApiException e) {
                        //下载失败
                        PathConfigConstant.isLoading = false;
                        Hawk.put("isLoading", PathConfigConstant.isLoading);
                        if (manager != null) {
                            manager.cancel(PathConfigConstant.NOTIFICATION_ID);
                        }
                        Toasty.normal(VersionService.this, "下载失败...", Toast.LENGTH_SHORT).show();
                    }
                });


    }


    /**
     * 安装apk
     *
     * @param file
     */
    private void installApk(File file) {
        Intent intent = new Intent("android.intent.action.VIEW");
        intent.addCategory("android.intent.category.DEFAULT");
        String type = "application/vnd.android.package-archive";
        Uri uri;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            intent = new Intent();
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.setAction(Intent.ACTION_VIEW);
            Uri uriForFile = FileProvider.getUriForFile(VersionService.this, VersionService.this.getApplicationContext().getPackageName() + ".provider", file);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.setDataAndType(uriForFile, VersionService.this.getContentResolver().getType(uriForFile));
        } else {
            uri = Uri.fromFile(file);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.setDataAndType(uri, type);
        }
        startActivity(intent);
    }


    /**
     * 设置通知
     */
    private void setNotification(int progress) {
        if (manager == null) {
            manager = (NotificationManager)
                    getSystemService(NOTIFICATION_SERVICE);
        }
        if (remoteViews == null) {
            remoteViews = new RemoteViews(getPackageName(), R.layout.notification_version);
            //自定义布局
            String appName = CommonUtils.getInstance().getAppName();
            remoteViews.setTextViewText(R.id.title, appName);
            remoteViews.setImageViewResource(R.id.logo, R.mipmap.ic_launcher);
            remoteViews.setProgressBar(R.id.progress_bar, 100, progress, false);
            remoteViews.setTextViewText(R.id.progress_txt, progress + "%");
        } else {
            remoteViews.setTextViewText(R.id.progress_txt, progress + "%");
            remoteViews.setProgressBar(R.id.progress_bar, 100, progress, false);
        }
        if (notification == null) {
//            PendingIntent p = PendingIntent.getActivity(VersionService.this, 0,
//                    new Intent(this, HomeActivity.class), 0);
//            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
//                NotificationChannel channel = new NotificationChannel("update", "updateApk", NotificationManager.IMPORTANCE_LOW);
//                Notification.Builder builder = new Notification.Builder(VersionService.this, "update");
//                channel.setSound(null, null);
//                channel.enableLights(true);
//                channel.enableVibration(false);
//                channel.setVibrationPattern(new long[]{0});
//                manager.createNotificationChannel(channel);
//                builder.setCustomContentView(remoteViews)
//                        .setSmallIcon(R.mipmap.ic_launcher)
//                        .setContentIntent(p)
//                        .setTicker("正在下载")
//                        .setWhen(System.currentTimeMillis());
//                notification = builder.build();
//            } else {
//                NotificationCompat.Builder builder = new NotificationCompat.Builder(VersionService.this);
//                builder.setCustomContentView(remoteViews)
//                        .setSmallIcon(R.mipmap.ic_launcher)
//                        .setContentIntent(p)
//                        .setTicker("正在下载")
//                        .setWhen(System.currentTimeMillis());
//                notification = builder.build();
//            }
//            notification.flags = Notification.FLAG_NO_CLEAR;
        }
        //发送通知
        manager.notify(PathConfigConstant.NOTIFICATION_ID, notification);
    }

}
